const ResponseMessage = require("../response/message");
const config = require("../config");
const jwt = require("../utils/jwt");

const log4js = require("log4js");
const logger = log4js.getLogger();


const {
  updateStudentLoginStatus,
  updateTeacherLoginStatus,
  updateDeanLoginStatus,
  updateAdminLoginStatus,
} = require("../persistent_api/loginApi");

// 校验 JWT - 登录态只要过期或者不合法都需要修改登录状态为为未登录并登出 前端验证时须传递 loginType 建议将登陆时的类型存储起来
exports.auth = async function (req, res, next) {

  async function updateStatus(loginType,id){
    console.log(id,"====",loginType);
    try{
      if(loginType === 1) await updateStudentLoginStatus(null,null,0,id);
      if(loginType === 2) await updateTeacherLoginStatus(null,null,0,id);
      if(loginType === 3) await updateDeanLoginStatus(null,null,0,id);
      if(loginType === 4) await updateAdminLoginStatus(null,null,0,id);
    }catch(error){
      logger.error(req.method + " - " + req.originalUrl + " - 网络错误")
      return res.send(new ResponseMessage(500, "网络错误", {}));
    }  
  }

  if (req.headers.token) {
    let {id,loginType} = req.body;  
    if (req.headers.token.split(".").length !== 3) {
      logger.warn(req.method + " - " + req.originalUrl + " - token 不合法")
      updateStatus(loginType,id);
      return res.send(new ResponseMessage(-1, "token 不合法", {}));
    }
    const responseMessage = jwt.verify(req.headers.token, config.secret);
    if (responseMessage.getCode() !== 2) { 
      updateStatus(loginType,id);
      res.status(201);
      res.send(responseMessage);
    } else {
      // if(req.responseMessage?.data?.pwd){
      //     delete req.responseMessage?.data?.pwd;
      // }
      req.responseMessage = responseMessage;
      next();
    }
  } else {
    res.status(201);
    logger.warn(req.method + " - " + req.originalUrl + " - token 缺失")
    res.send(new ResponseMessage(-1, "token 缺失", {}));
  }
};
